﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using RestSharp;
using Newtonsoft.Json.Linq;
using Tradier.Models;
using System.Web.Script.Serialization;
using System.Collections.Specialized;

namespace Tradier
{
    /// <summary>
    /// Summary description for Service
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {

        [WebMethod(EnableSession = true)]
        public string GetQuotes(string criteria)
        {
            try
            {
                var accessToken = Session["UserTradierAccessToken"];
                if (accessToken == null)
                {
                    return null;
                }
                else
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/markets/quotes?symbols={0}", criteria), Method.GET);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    var result = (client.Execute(request).Content);

                    return result;
                }
            }
            catch
            {
                return null;
            }
        }

        [WebMethod(EnableSession = true)]
        public string GetExpirationDates(string symbol)
        {
            try
            {
                var accessToken = Session["UserTradierAccessToken"];
                if (accessToken == null)
                {
                    return null;
                }
                else
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/markets/options/expirations?symbol={0}", symbol), Method.GET);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    var result = (client.Execute(request).Content);

                    return result;
                }
            }
            catch
            {
                return null;
            }
        }

        [WebMethod(EnableSession = true)]
        public string GetStrikes(string symbol, string date)
        {
            try
            {
                var accessToken = Session["UserTradierAccessToken"];
                if (accessToken == null)
                {
                    return null;
                }
                else
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/markets/options/strikes?symbol={0}&expiration={1}", symbol, date), Method.GET);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    var result = (client.Execute(request).Content);

                    return result;
                }
            }
            catch
            {
                return null;
            }
        }

        [WebMethod(EnableSession = true)]
        public string GetChain(string symbol, string date)
        {
            try
            {
                var accessToken = Session["UserTradierAccessToken"];
                if (accessToken == null)
                {
                    return null;
                }
                else
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/markets/options/chains?symbol={0}&expiration={1}", symbol, date), Method.GET);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    var result = (client.Execute(request).Content);

                    return result;
                }
            }
            catch
            {
                return null;
            }
        }

        [WebMethod(EnableSession = true)]
        public string PreviewOrder(CreateOrderModel order)
        {
            try
            {
                var accessToken = Session["UserTradierAccessToken"];
                if (accessToken == null)
                {
                    return null;
                }
                else
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/accounts/{0}/orders", order.account_id), Method.POST);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "Bearer " + accessToken);

                    request.AddParameter("preview", "true");

                    AppendParamsPreviewOrder(order, request);

                    var result = (client.Execute(request).Content);

                    return result;
                }
            }
            catch
            {
                return null;
            }
        }

        private void AppendParamsPreviewOrder(CreateOrderModel order, RestRequest request)
        {
            string orderKind = order.Class;
            if (!string.IsNullOrEmpty(orderKind))
            {
                request.AddParameter("class", orderKind);
            }

            if (!string.IsNullOrEmpty(order.Symbol))
            {
                request.AddParameter("symbol", order.Symbol);
            }

            if (!string.IsNullOrEmpty(order.Duration))
            {
                request.AddParameter("duration", order.Duration);
            }
            if (!string.IsNullOrEmpty(order.Side))
            {
                string side = "side";
                if (orderKind.Equals("combo"))
                {
                    side = "side[1]";
                }
                request.AddParameter(side, order.Side);
            }

            if (!string.IsNullOrEmpty(order.Quantity))
            {
                string quantity = "quantity";
                if (orderKind.Equals("combo"))
                {
                    quantity = "quantity[1]";
                }
                request.AddParameter(quantity, order.Quantity);
            }

            if (!string.IsNullOrEmpty(order.Type))
            {
                request.AddParameter("type", order.Type);
            }

            if (!string.IsNullOrEmpty(order.Price))
            {
                request.AddParameter("price", order.Price);
            }

            if (!string.IsNullOrEmpty(order.Stop))
            {
                request.AddParameter("stop", order.Stop);
            }

            if (!string.IsNullOrEmpty(order.option_symbol))
            {
                string optionSymbol = "option_symbol";
                if (orderKind.Equals("combo"))
                {
                    request.AddParameter("option_symbol[0]", "null");
                    optionSymbol = "option_symbol[1]";
                }
                request.AddParameter(optionSymbol, order.option_symbol);
            }

            if (!string.IsNullOrEmpty(order.Amount))
            {
                request.AddParameter("price", order.Amount);
            }

            if (!string.IsNullOrEmpty(order.ComboEquitySide))
            {
                request.AddParameter("side[0]", order.ComboEquitySide);
            }
            if (!string.IsNullOrEmpty(order.ComboEquityQuantity))
            {
                request.AddParameter("quantity[0]", order.ComboEquityQuantity);
            }

            if (!string.IsNullOrEmpty(order.MultilegParams))
            {
                NameValueCollection multilegParams = HttpUtility.ParseQueryString(order.MultilegParams);
                foreach (string item in multilegParams.AllKeys)
                {
                    if (item != null)
                    {
                        request.AddParameter(item, multilegParams[item]);
                    }
                }
            }
        }
    }
}
